package com.qq.ssm.service;

import com.qq.ssm.dao.AppCategoryDao;
import com.qq.ssm.entity.AppCategory;
import com.qq.ssm.vo.CategoryTreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategroyService {

    @Autowired
    AppCategoryDao appCategoryDao;

    public CategoryTreeVo tree() {
        //1.查询所有分类

        List<CategoryTreeVo> voList = new ArrayList<>();
        List<AppCategory> list = appCategoryDao.queryAllBy(new AppCategory());
        for (AppCategory appCategory : list) {
            CategoryTreeVo vo = new CategoryTreeVo();
            BeanUtils.copyProperties(appCategory,vo);
            voList.add(vo);
        }

        //2.改变结构 变成树形结构

        //找树的入口
        CategoryTreeVo tree = new CategoryTreeVo();
        for (CategoryTreeVo categoryTreeVo : voList) {
            if (categoryTreeVo.getParentid() == null){//这就是树的根
                //为这个根装填 一级分类
                tree=findChildren(categoryTreeVo,voList);
            }
        }
        return tree;
    }

    private CategoryTreeVo findChildren(CategoryTreeVo categoryTreeVo, List<CategoryTreeVo> voList) {
        categoryTreeVo.setChildren(new ArrayList<>());
        for (CategoryTreeVo treeVo : voList) {

            if (categoryTreeVo.getId() == treeVo.getParentid()){
                //装填进去
                categoryTreeVo.getChildren().add(treeVo);
                findChildren(treeVo,voList);
            }

        }
        return categoryTreeVo;
    }
}
